<script type="text/javascript">
function UploadPhotosController() {
		
	var noPhotosAvailable = jQuery('#noPhotosAvailable');
	var allPhotosContainer = jQuery('#allPhotosContainer');
	var coverPhotoImage = jQuery('#coverPhotoImage');
	var coverId = jQuery('#coverId');
	var btnDelete = jQuery('#deleteUploadedPhotos');
	var btnCover = jQuery('#btn_cover');
	
	var ELEMENT_NAME_PREFIX = "photo";
	
	var eventPhotos = new EventPhotosCollection();
	
	//Bindings	
	this.addPhoto = addPhoto;
	this.deleteSelectedPhotos = deleteSelectedPhotos;
	this.makeCoverPhoto = makeCoverPhoto;
	this.cancelChanges = cancelChanges;
	this.getImageContainer = getImageContainer;
	this.setCoverByPhotoId = setCoverByPhotoId;

	init();
			
	function init(){
		setButtonsVisibility();
	}
	
	function addPhoto(photoJSONObject){
		var elementName = ELEMENT_NAME_PREFIX + photoJSONObject.photoId;			
		var photoEntity = new Photo(photoJSONObject.photoId,photoJSONObject.url,elementName,photoJSONObject.thumbnailUrl);
		eventPhotos.addPhoto(photoEntity);
		
		var aPhotoContainer = jQuery('<div id="'+elementName+'" class="gridPhotoContainer" />'); 			  
		var galleryRef = jQuery('<a class="preview" />');		
		
							
		var image = jQuery('<img class="gridPhotoImage" >');		
		image.prop('src', photoEntity.getThumbnailUrl());

		image.click(function (event) {
			//Hace que no se redireccione a la imagen.
			event.preventDefault();

			var divContainer = getImageContainer(jQuery(this));
			
			if (jQuery(this).hasClass("gridPhotoImage")){
				jQuery(this).removeClass("gridPhotoImage");
				jQuery(this).addClass("gridPhotoImageSelected");
				divContainer.addClass("gridPhotoContainerSelected");
			}
			else{
				jQuery(this).removeClass("gridPhotoImageSelected");										
				jQuery(this).addClass("gridPhotoImage");
				divContainer.removeClass("gridPhotoContainerSelected");
			}
			
			setButtonsVisibility();
	    });
		
		galleryRef.append(image);				
		galleryRef.prop('href', photoEntity.getUrl())						  				

		aPhotoContainer.append(galleryRef);
		aPhotoContainer.appendTo(allPhotosContainer);
		
		showHideAvailableUnselectedPhotos();
	}
	
	function setButtonsVisibility(){
		var amountSelectedPhotos = jQuery('.gridPhotoImageSelected').size();
		
		if (amountSelectedPhotos == 1)
			btnCover.show();
		else
			btnCover.hide();
		
		if (amountSelectedPhotos > 0)
			btnDelete.show();
		else 
			btnDelete.hide();
		
	}
	
	function makeCoverPhoto(){
		var photosToBeCoverElements = jQuery('.gridPhotoImageSelected');
		
		if (photosToBeCoverElements.size() != 1)
			return;
		
		//Recupero la imagen seleccionada
		jQuery.each(photosToBeCoverElements,function(){
			var elementName=getImageContainer(jQuery(this)).prop('id');			
			setCoverByPhotoElementName(elementName);						
		});															
	}
	
	function setCoverByPhotoId(photoId){
		if(photoId != "0"){
			var elementName = ELEMENT_NAME_PREFIX + photoId	
			setCoverByPhotoElementName(elementName);	
		}
		else {
			setNullCover();
		}
	}
	
	function setCoverByPhotoElementName(elementName){
		var selectedPhoto = eventPhotos.getPhotoEntityByName(elementName);
		
		//La seteo en JS		
		eventPhotos.setCoverPhoto(selectedPhoto);
		
		//Seteo el ID en un hidden field
		coverId.val(selectedPhoto.getId());
					
		// cambio la imagen de la cover foto
		coverPhotoImage.attr('src',selectedPhoto.getUrl());	
	}
	
	function deleteSelectedPhotos(serverUrl,eventNumber) {
						
		//Se averigua que fotos va a borrar
		var photosToBeErased = jQuery('.gridPhotoImageSelected');
		var photoIds = [];
		
		var coverToBeErased = false;
		
		jQuery.each(photosToBeErased,function(){			
			var element = jQuery(this);
			var elementName=getImageContainer(element).prop('id');			
			var selectedPhoto = eventPhotos.getPhotoEntityByName(elementName);			
			photoIds.push(selectedPhoto.getId());						
			
			if (selectedPhoto == eventPhotos.getCoverPhoto())
				coverToBeErased = true;						
		});				
		
		var idsAsString = photoIds.toString();
		//Primero se borran las fotos en el servidor
		jQuery.ajax({
            url: serverUrl,//	,
            type: "POST",
            data: { "ids": idsAsString,
            		"eventNumber": eventNumber },            
            async:false,		                
            success: function(){		                    	
            	// Ahora se borran en el cliente
            	getImageContainer(photosToBeErased).remove();
            	if(coverToBeErased)
            		setNullCover();
            	showHideAvailableUnselectedPhotos();
            },
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });				
	}

	
	function cancelChanges(postServerUrl,nextUrl,eventNumber,eventId){
		jQuery.ajax({
			url: postServerUrl,
            type: "POST",		    
            data: {"eventId": eventId,
            	   "eventNumber": eventNumber}, 
            success: function(){		                	
            	window.location.replace(nextUrl);
            },
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });
	}
	
	function setNullCover(){
		coverPhotoImage.attr('src',"${resource(dir:'images', file: 'defaultImage.jpg')}");
		coverPhotoImage.attr('name',"0");
	}
	
	function getImageContainer(element){
		return element.parent().parent();
	}
	
	// Si no quedaron fotos seleccionadas se activa el No hay fotos disponibles
	function showHideAvailableUnselectedPhotos() {
		var eventPhotosContainers = jQuery('#allPhotosContainer > .gridPhotoContainer');
		
		if (eventPhotosContainers.length === 0)
			noPhotosAvailable.show();
		else
			noPhotosAvailable.hide();
	}	
}
</script>